package com.ft.service;


import com.ft.mapper.OrderMapper;
import com.ft.model.Order;
import com.ft.model.enums.OrderStatusChangeEventEnum;
import com.ft.model.enums.OrderStatusEnum;
import com.ft.statemachine.recipes.persist.PersistEnumStateMachineHandler;
import com.ft.statemachine.recipes.persist.PersistEnumStateMachineHandler.PersistEnumStateChangeListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.state.State;
import org.springframework.statemachine.transition.Transition;

/**
 * @author: zhangjianghua
 * @Date: 2018-10-10 10:53
 */
public class OrderStateService {
    private final PersistEnumStateMachineHandler handler;
    private final PersistEnumStateChangeListener listener = new OrderPersistStateChangeListener();

    @Autowired
    private OrderMapper orderMapper;

    public OrderStateService(PersistEnumStateMachineHandler handler) {
        this.handler = handler;
        this.handler.addPersistStateChangeListener(listener);
    }

    public boolean change(Long orderId, OrderStatusChangeEventEnum event) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        return handler.handleEventWithState(MessageBuilder.withPayload(event).setHeader("orderId", orderId).build(), order.getStatus());
    }

    private class OrderPersistStateChangeListener implements PersistEnumStateChangeListener<OrderStatusEnum, OrderStatusChangeEventEnum> {

        @Override
        public void onPersist(State<OrderStatusEnum, OrderStatusChangeEventEnum> state, Message<OrderStatusChangeEventEnum> message,
                              Transition<OrderStatusEnum, OrderStatusChangeEventEnum> transition, StateMachine<OrderStatusEnum, OrderStatusChangeEventEnum> stateMachine) {
            if (message != null && message.getHeaders().containsKey("orderId")) {
                Long orderId = message.getHeaders().get("orderId", Long.class);
                Order order = new Order();
                order.setId(orderId);
                order.setStatus(state.getId());
                orderMapper.updateByPrimaryKey(order);
            }
        }
    }

}
